package com.das.mechanic_base.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.das.mechanic_base.utils.X3ScreenUtils;

public class PathPointView extends View {
    private float mX;
    private float mY;
    private Paint mGesturePaint = null;
    private Path mPath = null;

    public boolean modify;

    public PathPointView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPath = new Path();//路径
        mGesturePaint = new Paint();//创建画笔
        mGesturePaint.setAntiAlias(true);
        mGesturePaint.setStyle(Paint.Style.STROKE);//样式
        mGesturePaint.setStrokeWidth(X3ScreenUtils.dip2px(3,context));//宽度
        mGesturePaint.setColor(Color.BLACK);//颜色
    }

    /**
     * 这个View的点击事件
     *
     * @param event
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touchDown(event);
                break;
            case MotionEvent.ACTION_MOVE:
                touchMove(event);
        }
        invalidate();// 更新绘制
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 通过画布绘制多点形成的图形
        canvas.drawPath(mPath, mGesturePaint);
    }

    /**
     * 手指点下屏幕时调用，获得手指点下的坐标
     *
     * @param event
     */
    private void touchDown(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        mX = x;
        mY = y;
        mPath.moveTo(x, y);// mPath绘制的绘制起点
    }

    /**
     * 手指在屏幕上滑动时调用
     *
     * @param event
     */
    private void touchMove(MotionEvent event) {
        modify = true;
        if (onToucheDraw!=null){
            onToucheDraw.onToucheDraw();
        }
        final float x = event.getX();
        final float y = event.getY();

        final float previousX = mX;
        final float previousY = mY;

        final float dx = Math.abs(x - previousX);
        final float dy = Math.abs(y - previousY);

        // 两点之间的距离大于等于3时，生成贝塞尔绘制曲线
        if (dx >= 3 || dy >= 3) {
            // 设置贝塞尔曲线的操作点为起点和终点的一半
            float cX = (x + previousX) / 2;
            float cY = (y + previousY) / 2;
            // 二次贝塞尔，实现平滑曲线；previousX, previousY为操作点，cX, cY为终点
            mPath.quadTo(previousX, previousY, cX, cY);
            // 第二次执行时，第一次结束调用的坐标值将作为第二次调用的初始坐标值
            mX = x;
            mY = y;
        }
    }

    /**
     * 重置绘制路线，即隐藏之前绘制的轨迹
     */
    public void reset() {
        mPath.reset();
        invalidate();// 更新绘制
    }
    public void setOnToucheDraw(OnToucheDraw onToucheDraw){
        this.onToucheDraw = onToucheDraw;
    }
    OnToucheDraw onToucheDraw;
    public interface OnToucheDraw{
        void onToucheDraw();
    }

}